from src.db_models.base import db
from src.llm_apis.select_api import select_api
from src.db_models.models import Term
from src.prompts import build_example_prompt


def get_terms_list():
    """从数据库中提取所有术语"""
    try:
        terms = db.session.query(Term.CN).all()  # 查询所有术语的CN字段
        terms_list = [term[0] for term in terms]  # 转换为简单的术语列表
        return terms_list
    except Exception as e:
        print(f"Error fetching terms: {e}")
        return []


def generate_term_results(cn_terms, model_choice):
    """
    根据术语列表从数据库查询翻译，并调用大模型生成例句。
    返回编号化的结果字典，格式为:
    {
        "1": {"chinese": "术语1", "english": "术语1的英文", "example": "术语1的英文例句"},
        "2": {"chinese": "术语2", "english": "术语2的英文", "example": "术语2的英文例句"},
        ...
    }
    """
    results = {}
    count = 1  # 初始化计数器

    for cn_term in cn_terms:
        cn_term = cn_term.strip()
        result = db.session.query(Term).filter(Term.CN == cn_term).first()

        # 待新增功能：优先调用术语库中的example，为空的话再生成example
        if result:
            english_term = result.EN

            # 使用 build_example_prompt 函数生成 prompt
            example_prompt = build_example_prompt(english_term)

            # 调用根据选择的模型生成例句
            example_sentence = select_api(model_choice, example_prompt)

            # 按照指定的格式存储结果
            results[str(count)] = {
                "chinese": cn_term,
                "english": english_term,
                "example": example_sentence
            }
        else:
            results[str(count)] = {
                "chinese": cn_term,
                "english": "未找到对应的英文翻译",
                "example": ""
            }

        count += 1  # 每处理一个术语增加计数器

    return results